# -*- coding:utf8 -*-
import json
import typing
import ddddocr
import traceback
from scrapy import Request
from squirrel_core.item.procedure_item import ProcedureItem
from squirrel_core.frame.spider_makaka import MakakaSpider


class chengdufeiyi_score(MakakaSpider):
    name = "chengdufeiyi_score"
    start_url = "https://api-changzheng.chinaath.com/changzheng-website-center-api/api/official/website/domain/name/selectByDomainName?domainName=chengdu.shuzixindong.com"
    img_url = "https://api-changzheng.chinaath.com/changzheng-basic-center-api/api/imageVerify/getUniqueIdByBusinessType?imageVerifyBusinessType=2"
    yzm_url = "https://api-changzheng.chinaath.com/changzheng-basic-center-api/api/imageVerify/getVerifyCode?uniqueId={}"
    score_url = "https://api-changzheng.chinaath.com/changzheng-score-center-api/api/race/score/user/getCertPathByVerificationCode"
    header = {
        "Host": "api-changzheng.chinaath.com",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:137.0) Gecko/20100101 Firefox/137.0",
        "Accept": "application/json, text/plain, */*",
        "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "Content-Type": "application/json",
        "Origin": "https://chengdu.shuzixindong.com",
        "Referer": "https://chengdu.shuzixindong.com/"
    }

    def get_ext_requests_or_urls(self, data=None):
        if data and isinstance(data, str):
            data = json.loads(data)
        if data and isinstance(data, typing.MutableMapping):
            card_num = data.get("card_num", "")
            yield Request(url=self.start_url, callback=self.parse, dont_filter=True,
                          cb_kwargs={"card_num": card_num}, errback=self.err_parse)

    def parse(self, response, **kwargs):
        try:
            item = ProcedureItem()
            item["_result"] = {
                "note": "任务启动成功",
                "code": 200,
                "success": True
            }
            yield item
            self.logger.info("开始获取raceid")
            data = json.loads(response.text).get("data", "")
            race_id = data.get("raceId", "")
            kwargs.update({"race_id": race_id})
            yield Request(url=self.img_url, callback=self.img_id_parse, dont_filter=True,
                          cb_kwargs=kwargs, errback=self.err_parse)
        except Exception:
            self.logger.error(f"请求raceid时出错：{traceback.format_exc()}")

    def img_id_parse(self, response, **kwargs):
        try:
            self.logger.info("开始获取imageUniqueId")
            data = json.loads(response.text).get("data", "")
            kwargs.update({"imageUniqueId": data})
            url = self.yzm_url.format(data)
            yield Request(url=url, callback=self.yzm_parse, dont_filter=True, cb_kwargs=kwargs, errback=self.err_parse)
        except Exception:
            self.logger.error(f"请求imageUniqueId时出错：{traceback.format_exc()}")

    def yzm_parse(self, response, **kwargs):
        try:
            self.logger.info("开始打码")
            race_id = kwargs.get("race_id", "")
            image_id = kwargs.get("imageUniqueId", "")
            card_num = kwargs.get("card_num", "")
            ocr = ddddocr.DdddOcr(show_ad=False, beta=True)
            yzm = ocr.classification(response.body)
            score_data = {"raceId": int(race_id), "cardNum": card_num,
                          "imageUniqueId": image_id, "imageVerifyCode": yzm}
            yield Request(url=self.score_url, callback=self.score_parse, method="POST", headers=self.header,
                          body=json.dumps(score_data), dont_filter=True, cb_kwargs=kwargs, errback=self.err_parse)
        except Exception:
            self.logger.error(f"打码时出错：{traceback.format_exc()}")

    def score_parse(self, response, **kwargs):
        try:
            msg = json.loads(response.text).get("msg", "")
            if msg == "验证码错误":
                self.logger.info(f"查询成绩信息时验证码错误，重新打码")
                yield Request(url=self.start_urls[0], callback=self.parse, dont_filter=True,
                              cb_kwargs=kwargs, errback=self.err_parse)
            else:
                self.logger.info("开始查询成绩信息")
                data = json.loads(response.text).get("data", [])
                if data:
                    score_img = [f"https://img.shuzixindong.com{path}" for path in data]
                else:
                    score_img = "没有成绩"
                score_data = score_img
                result = self.result_item_assembler(response)
                result['result_data'] = {'score_data': score_data}
                yield result
        except Exception:
            self.logger.error(f"请求成绩信息时出错：{traceback.format_exc()}")

    def err_parse(self, failure):
        self.logger.warning(f"请求失败：{failure.request.url},错误原因:{traceback.format_exc()}")
